<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
    Array.prototype.myForEach = function(callback,thisArg){
        if(typeof callback !== 'function') throw new TypeError('callback is not a function')
        const that = thisArg !== null && thisArg !== undefined ? thisArg : this
        for(let i = 0;i < this.length;i++){
            if(i in this){
                callback.call(that,this[i],i,this)
            }
        }
    }
    let arr = [1,2,3]
        // 基础功能测试
    arr.myForEach((num) => console.log(num * 2)); // 应输出 2,4,6

    // thisArg 绑定测试
    const obj = { multiplier: 10 };
    [1,2].myForEach(function(num) {
        console.log(num * this.multiplier); // 应输出 10,20
    }, obj);

    // 稀疏数组测试
    const sparseArr = [1,,3];
    sparseArr.myForEach((item, idx) => {
        console.log(`Index ${idx}:`, item); // 应跳过索引1
    });

    // 非函数回调测试
    try {
        [1].myForEach("not function"); // 应抛出 TypeError
    } catch(e) {
        console.log(e)
    }

    // 修改原数组测试
    const mutatingArr = [1,2,3];
    mutatingArr.myForEach((item, idx, arr) => {
        arr[idx] = item * 2; // 应修改为 [2,4,6]
    });
    console.log(mutatingArr);

    // 类数组对象测试
    const arrayLike = { 0: 'a', 1: 'b', length: 2 };
    Array.prototype.myForEach.call(arrayLike, (item) => console.log(item)); // 应输出 'a','b'

</script>
</html>